import { createVNode, render } from 'vue';
import MessageComponent from './MessageBox.vue';

let seed = 1;
const messageInstances: any[] = [];

const Message = {
  success(content: string, options = {}) {
    return this.show('success', content, options);
  },
  warning(content: string, options = {}) {
    return this.show('warning', content, options);
  },
  info(content: string, options = {}) {
    return this.show('info', content, options);
  },
  error(content: string, options = {}) {
    return this.show('error', content, options);
  },
  show(type: 'success' | 'warning' | 'info' | 'error', content: string, options: any) {
    const id = `message_${seed++}`;
    const offset = options.offset || 80;
    const position = options.position || 'top';

    // 计算偏移量
    let verticalOffset = offset;
    messageInstances.forEach(({ vm }) => {
      verticalOffset += (vm.el?.offsetHeight || 0) + 16;
    });

    // 创建容器
    const container = document.createElement('div');

    // 清除方法
    const remove = () => {
      render(null, container);
      document.body.removeChild(container);
      const index = messageInstances.findIndex(instance => instance.id === id);
      if (index !== -1) {
        messageInstances.splice(index, 1);
        // 重新计算位置
        messageInstances.forEach((instance, i) => {
          const verticalOffset = offset + i * (instance.vm.el?.offsetHeight + 16);
          instance.vm.component.props.offset = verticalOffset;
        });
      }
    };

    // 创建 vnode
    const vnode = createVNode(MessageComponent, {
      id,
      type,
      content,
      offset: verticalOffset,
      position,
      duration: options.duration,
      onClose: remove
    });

    // 渲染
    render(vnode, container);
    document.body.appendChild(container);

    // 保存实例
    messageInstances.push({ id, vm: vnode });

    return {
      close: remove
    };
  }
};

export default Message;
